package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tanjie
 */
@Service
public class ReportServiceImpl implements ReportService {
    private static final Logger log = LoggerFactory.getLogger(ReportServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin 开始日期
     * @param end   结束日期
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistic(LocalDate begin, LocalDate end) {
        //当前集合用来存放从begin到end范围的每天的日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);

        //日期计算
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //StringUtils.join(dateList, ",")

        //存放每天的营业额
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询当前list中的每一个日期对应的营业额（状态为：已完成）

            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //select sum(amount) from orders where order_time > ? and order_time < ? and status = 5
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnOver = orderMapper.sumByMap(map);
            turnOver = turnOver == null ? 0 : turnOver;
            turnoverList.add(turnOver);
        }
        //将List转换为String
        //StringUtils.join(turnoverList, ",");

        //封装并返回
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistic(LocalDate begin, LocalDate end) {
        //当前集合用来存放从begin到end范围的每天的日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);

        //日期计算
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天的新增的用户数量 select count(id) from user where create_time < ? and create_time > ?
        List<Integer> newUserList=new ArrayList<>();
        //存放每天的总用户数量  select count(id) from user where create_time <= NOW()
        List<Integer> totalUserList=new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //查询当前list中的每一个日期对应的营业额（状态为：已完成）

            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();

            map.put("end",endTime);
            //总的用户数量
            Integer totalUser =userMapper.countByMap(map);

            map.put("begin",beginTime);
            //新用户数量
            Integer newUser =userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 动态获取指定时间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistic(LocalDate begin, LocalDate end) {
        //当前集合用来存放从begin到end范围的每天的日期
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);

        //日期计算
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //有效订单集合
        List<Integer> validOrderCountList=new ArrayList<>();
        //订单总数集合
        List<Integer> totalOrderCountList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询订单总数、有效订单数
            //查询每天的订单总数 select count(id) from orders where order_time > beginTime and order_time < endTime
            //查询每天的有效订单数  select count(id) from orders where order_time > beginTime and order_time < endTime and status = 5

            //有效订单数
            Integer orderCount = getOrderCount(beginTime,endTime,null);
            //总数
            Integer totalOrderCount =getOrderCount(beginTime,endTime,Orders.COMPLETED);

            //添加到相对应的集合中
            totalOrderCountList.add(totalOrderCount);//总数
            validOrderCountList.add(orderCount);//有效订单数
        }

        //计算所有的订单数
        Integer totalOrderCount = totalOrderCountList.stream().reduce(Integer::sum).get();

        //计算有效订单数
        Integer validOrderCount= validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = (double) 0;
        if(totalOrderCount != 0) {
             orderCompletionRate = (double) (validOrderCount/totalOrderCount);
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(totalOrderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return  orderMapper.countByMap(map);
    }


    /**
     * 销量排名Top10
     * @param begin 开始日期
     * @param end   结束日期
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        log.info("销量排名Top10：{}，{}", begin, end);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);


        // 1. 提取所有name，用逗号拼接成字符串
        String nameList = salesTop10.stream()
                .map(GoodsSalesDTO::getName)  // 提取name属性
                .collect(Collectors.joining(","));  // 用逗号拼接

        // 2. 提取所有number，转换为字符串后用逗号拼接
        String numberList = salesTop10.stream()
                .map(dto -> dto.getNumber().toString())  // 提取number并转为String
                .collect(Collectors.joining(","));  // 用逗号拼接

        // 3. 封装到VO并返回
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出Excel，近三十天地数据
     */
    @Override
    public void exportBussinessData(HttpServletResponse response) {
        //1，查询数据库，获取营业数据(最近30天)
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        //2，通过POI将数据写入到Excel文件中

        //通过反射获取当前类的实例并通过获取类加载器得到模板文件的输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //通过模板文件创建一个新的Excel文件
            try {
                XSSFWorkbook excel = new XSSFWorkbook(in);
                //填充概览数据
                XSSFSheet sheet1= excel.getSheet("sheet1");
                sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
                //第4行
                XSSFRow row4 = sheet1.getRow(3);
                row4.getCell(2).setCellValue(businessDataVO.getTurnover());
                row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
                //第五行 有效订单，平均客单价
                XSSFRow row5 = sheet1.getRow(4);
                row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
                row5.getCell(3).setCellValue(businessDataVO.getUnitPrice());
                //3，通过输出流对象将Excel文件下载到客户端浏览器
                ServletOutputStream outputStream = response.getOutputStream();


                //填充明细数据
                for (int i = 0 ;i < 30; i++ ){
                    LocalDate date=dateBegin.plusDays(i);

                    //查询某一天的明细数据
                    BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                    //获取某一行
                    XSSFRow row = sheet1.getRow(7 + i);

                    //获取某一个单元格        日期	"	营业额"	"	有效订单"	订单完成率	平均客单价	新增用户数
                    row.getCell(1).setCellValue(String.valueOf(date));
                    row.getCell(2).setCellValue(businessData.getTurnover());
                    row.getCell(3).setCellValue(businessData.getValidOrderCount());
                    row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                    row.getCell(5).setCellValue(businessData.getUnitPrice());
                    row.getCell(6).setCellValue(businessData.getNewUsers());

                }

                excel.write(outputStream);

                //关闭资源
                outputStream.close();
                excel.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

    }
}
